//
//  xsBossIPBackgroundView.m
//  digital_robot_demo
//
//  Created by xskj on 2024/8/29.
//  选择背景音乐
// @[@"我的",@"欢快",@"营销类",@"咨询",@"轻音乐类",@"卡点",@"纯音乐",@"舒缓旋律",@"轻快节奏",@"动感",@"企业宣传"]

#import "xsBossIPBackgroundView.h"
  
#define xrandomColor  [UIColor colorWithRed:(arc4random() %255)/255.0f green:(arc4random() %255)/255.0f blue:(arc4random() %255)/255.0f alpha:1.0f]

@interface xsBossIPBackgroundView()<UIScrollViewDelegate>

@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIButton *xsSettingButton;
@property (nonatomic, strong) UILabel *topTitleLabel;
@property (nonatomic, strong) UIButton *xButton;// x按钮

@property (nonatomic, strong) UIButton *uploadAudioButton;//


@property (nonatomic, strong) UIScrollView *buttonsBgScrollView;
//@property (nonatomic, strong) NSArray *buttons;
@property (nonatomic, strong) UIView *buttonsBgView;

@property (nonatomic, strong) NSMutableArray *musicTagMarray;

@property (nonatomic,strong)xsBossIPBackgroundTableView *BossIPBackgroundTableView;

@end

@implementation xsBossIPBackgroundView


- (NSMutableArray *)musicTagMarray{
    if(!_musicTagMarray){
        _musicTagMarray = [[NSMutableArray alloc] init];
    }
    return _musicTagMarray;
}

- (instancetype)init{
    
    if (self = [super init]) {
        self.backgroundColor = UIColor.blackColor;
        
        
        [self addSubview:self.topView];
        
        [self.topView addSubview:self.xsSettingButton];
        [self.topView addSubview:self.topTitleLabel];
        [self.topView addSubview:self.xButton];
        
        [self addSubview:self.buttonsBgScrollView];
            
        [self.buttonsBgScrollView addSubview:self.buttonsBgView];
        
        [self addSubview:self.uploadAudioButton];
        
//
        
        //[self addSubview:self.BossIPBackgroundTableView];
            
            // 创建按钮数组
//        self.buttons = buttonTitles;//@[@"Tab1", @"Tab2", @"Tab3"];
            
        
        
    }
    return self;
}


- (UIView *)buttonsBgView{
    if(!_buttonsBgView){
        _buttonsBgView = [[UIView alloc] init];
        _buttonsBgView.backgroundColor = UIColor.blackColor;
    }
    return _buttonsBgView;
}


- (UIScrollView *)buttonsBgScrollView
{
    if(!_buttonsBgScrollView){
        _buttonsBgScrollView = [[UIScrollView alloc] init];
        _buttonsBgScrollView.backgroundColor = UIColor.clearColor;
        
        _buttonsBgScrollView.delegate = self;
        //_buttonsBgScrollView.pagingEnabled = YES;
        _buttonsBgScrollView.showsHorizontalScrollIndicator = NO;
    }
    return _buttonsBgScrollView;
}



-(void)layoutSubviews{
    [super layoutSubviews];
    //_recorder.preViewLayer.frame = self.frame;
    
    NSLog(@"layoutSubviews--self.bounds==%@",NSStringFromCGRect(self.bounds));
    
    
}

- (void)xsChangeFrame{
    
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left).offset(10);
        make.top.equalTo(self.mas_top);//.offset(10);
        make.right.equalTo(self.mas_right).offset(-10);
        make.height.mas_equalTo(50);
    }];
    
    [self.xsSettingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.topView.mas_left);//.offset(10);
        make.centerY.equalTo(self.topView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(35, 35));
    }];
    
    [self.xButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.topView.mas_right);//.offset(10);
        make.centerY.equalTo(self.topView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(35, 35));
    }];
    
    [self.topTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.topView);
    }];
    
    
    
    self.buttonsBgScrollView.frame = CGRectMake(0, 50+10, self.bounds.size.width, 40);
    
    
//    [self.BossIPBackgroundTableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.mas_left);//.offset(10);
//        make.top.equalTo(self.buttonsBgScrollView.mas_bottom).offset(10);
//        make.right.equalTo(self.mas_right);//.offset(-10);
//        make.bottom.equalTo(self.mas_bottom);//.offset(-10);
//    }];
//    [self.BossIPBackgroundTableView reloadData];
    
    [self getmusicTagListData];
}

- (void)xsReloadTabelViewDataWithTag:(NSInteger)tg{
    
//    NSString *tempStr = @"比赛都是同场竞技，怎么看待你们两位之间的关系？”听到记者的提问，残奥会“四朝元老”、在巴黎收获第六冠的场地自行车选手李樟煜和后起之秀梁伟聪瞬间笑弯了腰";
//    NSMutableArray *tempMarr = [NSMutableArray new];
//    
//    NSArray *timeArr = @[@"05:00",@"01:20",@"04:20",@"01:23",@"02:30"];
//    
//    for (int i =0; i<26; i++) {
//        xsBossIPBackgroundTableViewCellModel *md = [xsBossIPBackgroundTableViewCellModel new];
//        md.iconSourceUrl = @"bossIPDefaultImage";
//        
//        int leth = (int)tempStr.length;
//        int indexxx = arc4random()%leth;
//        NSString *musicTitle = @"";
//        if(indexxx>(leth-8)){
//            musicTitle = [tempStr substringFromIndex:indexxx];
//        }
//        else{
//            musicTitle = [tempStr substringWithRange:NSMakeRange(indexxx, 7)];
//        }
//        md.musicNameString = musicTitle;
//        
//        int timIdex = arc4random()%(timeArr.count);
//        md.timeCountString = [NSString stringWithFormat:@"%@",timeArr[timIdex]];
//        
//        [tempMarr addObject:md];
//    }
//    
//    [self.BossIPBackgroundTableView xsChangeData:tempMarr];
    BOOL IsMeSta = NO;
    if(tg!=0){
        IsMeSta = NO;
    }
    else{
        IsMeSta = YES;
    }
//    [self.BossIPBackgroundTableView reloadData];
    
    if(_BossIPBackgroundTableView){
        [_BossIPBackgroundTableView removeFromSuperview];
        _BossIPBackgroundTableView = nil;
    }
    self.BossIPBackgroundTableView = [[xsBossIPBackgroundTableView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height) style:UITableViewStylePlain withIsMe:IsMeSta];
    _BossIPBackgroundTableView.showsVerticalScrollIndicator = NO;
    _BossIPBackgroundTableView.backgroundColor = UIColor.clearColor;//COLOR_viewVCBgcolor;
    _BossIPBackgroundTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _BossIPBackgroundTableView.separatorColor = UIColor.clearColor;
    _BossIPBackgroundTableView.showsVerticalScrollIndicator = NO;
    
    [self addSubview:_BossIPBackgroundTableView];
    XSWeakSelf;
    _BossIPBackgroundTableView.tableViewCellDeleteCallBackBlock = ^(xsBossIPBackgroundTableViewCellModel * _Nonnull Dmodel) {
        NSLog(@"tableViewCellDeleteCallBackBlock.title111==%@\n",Dmodel.title);
        
        if([weakSelf.delegate respondsToSelector:@selector(xsBossIPBackgroundTabelViewCellDeleteButtonBeClick:)]){
            [weakSelf.delegate xsBossIPBackgroundTabelViewCellDeleteButtonBeClick:Dmodel];
        }
    };
    _BossIPBackgroundTableView.tableViewCellUseButtonCallBackBlock = ^(xsBossIPBackgroundTableViewCellModel * _Nonnull umodel) {
        NSLog(@"tableViewCellUseButtonCallBackBlock.title222==%@\n",umodel.title);
        
        if([weakSelf.delegate respondsToSelector:@selector(xsBossIPBackgroundViewPlayAudioButtonBeClick:)]){
            [weakSelf.delegate xsBossIPBackgroundViewPlayAudioButtonBeClick:umodel];
        }
    };
    _BossIPBackgroundTableView.tableViewCellBeClickCallBackBlock = ^(xsBossIPBackgroundTableViewCellModel * _Nonnull xsCellModel) {
        NSLog(@"tableViewCellBeClickCallBackBlock.title222==%@\n",xsCellModel.title);
        
        if([weakSelf.delegate respondsToSelector:@selector(xsBossIPBackgroundTabelViewCellBeClick:)]){
            [weakSelf.delegate xsBossIPBackgroundTabelViewCellBeClick:xsCellModel];
        }
    };
    
    [self.BossIPBackgroundTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_left);//.offset(10);
        make.top.equalTo(self.buttonsBgScrollView.mas_bottom).offset(10);
        make.right.equalTo(self.mas_right);//.offset(-10);
        make.bottom.equalTo(self.mas_bottom);//.offset(-10);
    }];
    [self.BossIPBackgroundTableView xsTableDataWithTagId:tg whitKeyWord:@""];
}

- (void)updateConstraints{
    [super updateConstraints];
//    
//    __weak __typeof (&*self)weakSelf = self;
    
    NSLog(@"updateConstraints");
    
    
    
    
}



//- (xsBossIPBackgroundTableView *)BossIPBackgroundTableView {
//    if (!_BossIPBackgroundTableView) {
//        
//        NSString *tempStr = @"比赛都是同场竞技，怎么看待你们两位之间的关系？”听到记者的提问，残奥会“四朝元老”、在巴黎收获第六冠的场地自行车选手李樟煜和后起之秀梁伟聪瞬间笑弯了腰";
//        NSMutableArray *tempMarr = [NSMutableArray new];
//        
//        NSArray *timeArr = @[@"05:00",@"01:20",@"04:20",@"01:23",@"02:30"];
//        
//        for (int i =0; i<26; i++) {
//            xsBossIPBackgroundTableViewCellModel *md = [xsBossIPBackgroundTableViewCellModel new];
//            md.iconSourceUrl = @"bossIPDefaultImage";
//            
//            int leth = (int)tempStr.length;
//            int indexxx = arc4random()%leth;
//            NSString *musicTitle = @"";
//            if(indexxx>(leth-8)){
//                musicTitle = [tempStr substringFromIndex:indexxx];
//            }
//            else{
//                musicTitle = [tempStr substringWithRange:NSMakeRange(indexxx, 7)];
//            }
//            md.musicNameString = musicTitle;
//            
//            int timIdex = arc4random()%(timeArr.count);
//            md.timeCountString = [NSString stringWithFormat:@"%@",timeArr[timIdex]];
//            
//            [tempMarr addObject:md];
//        }
//        
//        
//        _BossIPBackgroundTableView = [[xsBossIPBackgroundTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain withDataArray:[NSArray arrayWithArray:tempMarr] withIsMe:YES];
////_BossIPBackgroundTableView.delegate = self;
////_BossIPBackgroundTableView.dataSource = self;
////_BossIPBackgroundTableView.rowHeight = 50;
//        _BossIPBackgroundTableView.showsVerticalScrollIndicator = NO;
//        //        _BossIPBackgroundTableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 0.1)];
//        //        _BossIPBackgroundTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 0.1)];
//        _BossIPBackgroundTableView.backgroundColor = UIColor.clearColor;//COLOR_viewVCBgcolor;
//        _BossIPBackgroundTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _BossIPBackgroundTableView.separatorColor = UIColor.clearColor;
//        
////_BossIPBackgroundTableView.autoresizesSubviews = YES;
////_BossIPBackgroundTableView.autoresizingMask = YES;
//        _BossIPBackgroundTableView.showsVerticalScrollIndicator = NO;
//        
////// 让高度自动计算 不然有时候present时cell会坍塌
////_BossIPBackgroundTableView.rowHeight = UITableViewAutomaticDimension;
////_BossIPBackgroundTableView.estimatedRowHeight = 110;
////_BossIPBackgroundTableView.autoresizesSubviews = YES;
//        
//        //    @"empty"
//        //            self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"empty"
//        //             titleStr:@"暂无溯源文件"
//        //            detailStr:@""];
//        
//        //            self.tableView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
//        //                self.page = 1;
//        //                [self.dataArray removeAllObjects];
//        //
//        //                [self getFindTraceParseQueue];
//        //
//        //            }];
//        //
//        //            self.tableView.mj_footer= [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
//        //                ++self.page;
//        //                [self getFindTraceParseQueue];
//        //            }];
//        
//        
//    }
//    return _BossIPBackgroundTableView;
//}


- (UIView *)topView{
    
    if(!_topView){
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = UIColor.clearColor;
    }
    return _topView;
}



- (UIButton *)xButton{
    if (!_xButton) {
        _xButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _xButton.backgroundColor = UIColor.clearColor;
        [_xButton addTarget:self action:@selector(xButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_xButton setImage:[UIImage imageNamed:@"xsBossgou"] forState:UIControlStateNormal];
        
    }
    return _xButton;
}
- (void)xButtonAction:(UIButton *)btn{
    NSLog(@"xButtonAction\n\n");
   
    if([self.delegate respondsToSelector:@selector(xsBossIPBackgroundViewCloseButtonBeClick:)]){
        [self.delegate xsBossIPBackgroundViewCloseButtonBeClick:btn];
    }
}

- (UIButton *)xsSettingButton{
    if (!_xsSettingButton) {
        _xsSettingButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _xsSettingButton.backgroundColor = UIColor.clearColor;
        [_xsSettingButton addTarget:self action:@selector(xsSettingButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_xsSettingButton setImage:[UIImage imageNamed:@"xsBossIPSetting"] forState:UIControlStateNormal];
        _xsSettingButton.hidden = YES;
    }
    return _xsSettingButton;
}
- (void)xsSettingButtonAction:(UIButton *)btn{
    NSLog(@"xsSettingButtonAction\n\n");
   
//    if([self.delegate respondsToSelector:@selector(xsBossIPBackgroundViewSettingButtonBeClick:)]){
//        [self.delegate xsBossIPBackgroundViewSettingButtonBeClick:btn];
//    }
}
- (UILabel *)topTitleLabel {
    if (!_topTitleLabel) {
        _topTitleLabel = [[UILabel alloc] init];
        _topTitleLabel.backgroundColor = UIColor.clearColor;
        _topTitleLabel.font = [UIFont systemFontOfSize:21];// FontSemibold(17);
        _topTitleLabel.textColor = UIColor.whiteColor;//COLOR_TextGray9B;
        _topTitleLabel.numberOfLines = 1;
        _topTitleLabel.text = @"选择背景音";
        _topTitleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _topTitleLabel;
}


- (UIButton *)uploadAudioButton{
    if (!_uploadAudioButton) {
        _uploadAudioButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _uploadAudioButton.backgroundColor = UIColor.clearColor;
        _uploadAudioButton.titleLabel.font = Font(14);
        [_uploadAudioButton setTitleColor:COLOR_White forState:UIControlStateNormal];
        [_uploadAudioButton addTarget:self action:@selector(uploadAudioButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_uploadAudioButton setTitle:@"上传音频(40M内)" forState:UIControlStateNormal];
    }
    return _uploadAudioButton;
}

- (void)uploadAudioButtonAction:(UIButton *)btn{
    XSLog(@"uploadAudioButtonAction\n\n");
    
}


// 获取tag分类列表
- (void)getmusicTagListData
{
//
    
    XSWeakSelf;

    
//    NSString *tempUrl = @"https://mall219.writemall.com/bossapi/music/tagList";
    NSString *tempUrl = [NSString stringWithFormat:@"%@%@",API_BASEURL_BossIP,@"music/tagList"];

    NSDictionary *pramerDict = @{};
    
    [[ZYFDataManager sharedInstance] POST:tempUrl dict:pramerDict succeed:^(id data) {
        
        NSLog(@"背景音乐分组数据--data==%@\n",data);
        
        NSDictionary *dictData = data;
        if([dictData isKindOfClass:[NSDictionary class]]){
            if([dictData[@"code"] isKindOfClass:[NSNumber class]]||[dictData[@"code"] isKindOfClass:[NSString class]]){
                NSInteger codeInt = [dictData[@"code"] integerValue];
                if(codeInt==200){
                    
                    if([dictData[@"data"] isKindOfClass:[NSArray class]]){
                        NSArray *dataArr3  = dictData[@"data"];
                        
                        if(dataArr3.count>0){
                            for (int ii=0; ii<dataArr3.count; ii++) {
                                NSDictionary *tempFinalDict = dataArr3[ii];
                                xsMusicTagModel *md = [xsMusicTagModel yy_modelWithDictionary:tempFinalDict];
                                if([tempFinalDict[@"id"] isKindOfClass:[NSNumber class]]||
                                   [tempFinalDict[@"id"] isKindOfClass:[NSString class]]){
                                   NSString *tempIdStr = [NSString stringWithFormat:@"%ld",[tempFinalDict[@"id"] integerValue]];
                                    md.Id = [tempIdStr integerValue];
                                }
                                [weakSelf.musicTagMarray addObject:md];
                            }
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf createCategryView];
                            });
                        }
                    }
                    
                }
            }
        }
        
        
    } failure:^(NSDictionary *error) {
        NSLog(@"getAudioDataWithAspectRatio--error.description==%@\n",error.description);
    }];
}

- (void)createCategryView{
    
    
    UIFont *btnFont = Font(16);
    UIButton *lastButton;
    UIButton *firstButton;
    // 添加按钮到滚动视图
    for (int i = 0; i < self.musicTagMarray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        xsMusicTagModel *tempMd = self.musicTagMarray[i];
        NSString *buttonTitleStr = tempMd.name;
        
        CGFloat buttonW = [buttonTitleStr calculateWidth:btnFont withHeight:40]+25.0;
        
//        button.frame = CGRectMake(i * buttonW, 0, buttonW, 40);
        if(lastButton){
            button.frame = CGRectMake(CGRectGetMaxX(lastButton.frame), 0, buttonW, 40);
            button.titleLabel.font = Font(16);
        }
        else{
            firstButton = button;
            button.frame = CGRectMake(0, 0, buttonW, 40);
            button.titleLabel.font = FontBoldMT(18);
        }
        button.backgroundColor = UIColor.clearColor;//xrandomColor;
        [button setTitle:buttonTitleStr forState:UIControlStateNormal];
        [button setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        
        [button addTarget:self action:@selector(topTagListButtonBeClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = tempMd.Id;
        [self.buttonsBgView addSubview:button];
        lastButton = button;
    }

    // 设置内容视图的尺寸
    self.buttonsBgView.frame = CGRectMake(0, 0, CGRectGetMaxX(lastButton.frame), 40);
    self.buttonsBgScrollView.contentSize = self.buttonsBgView.frame.size;
    
    

    if(self.musicTagMarray.count>0){
        [self topTagListButtonBeClick:firstButton];
    }
}

#pragma mark 顶部分类标题被点击
- (void)topTagListButtonBeClick:(UIButton *)sender {
    NSInteger Id = sender.tag;
    NSLog(@"Selected--Id==%ld\n", (long)Id);
    
    if(Id==0){
        self.uploadAudioButton.hidden = NO;
        
        CGFloat nuploadAudioButtonW = 140;
        CGFloat nuploadAudioButtonX = self.bounds.size.width-10-nuploadAudioButtonW;
        CGFloat nuploadAudioButtonY = 50+10+2.0;
        CGFloat nuploadAudioButtonH = 35;
        self.uploadAudioButton.frame = CGRectMake(nuploadAudioButtonX, nuploadAudioButtonY, nuploadAudioButtonW, nuploadAudioButtonH);
        self.uploadAudioButton.backgroundColor = UIColor.blueColor;
        self.uploadAudioButton.layer.cornerRadius = 6.0;
        self.uploadAudioButton.layer.masksToBounds = YES;
        
        
        self.buttonsBgScrollView.frame = CGRectMake(0, 50+10, CGRectGetMinX(self.uploadAudioButton.frame)-10, 40);
    }
    else{
        self.uploadAudioButton.hidden = YES;
        
        self.buttonsBgScrollView.frame = CGRectMake(0, 50+10, self.bounds.size.width, 40);
    }
    
    
    //xsMusicTagModel *tempMd = self.musicTagMarray.firstObject;
    for (UIButton *tempButton in self.buttonsBgView.subviews) {
        
        if([tempButton isKindOfClass:[UIButton class]]){
            if(tempButton.tag==Id){
                tempButton.titleLabel.font = FontBoldMT(16);
            }
            else
            {
                tempButton.titleLabel.font = Font(18);
            }
        }
    }
    
    [self xsReloadTabelViewDataWithTag:Id];
    
    for (xsMusicTagModel *tempFindTagModel in self.musicTagMarray) {
        if(tempFindTagModel.Id==Id){
            
            NSLog(@"点击的标签名tempFindTagModel.name==%@\n  tempModel.Id==%ld\n",tempFindTagModel.name,tempFindTagModel.Id);
            
            if([self.delegate respondsToSelector:@selector(xsBossIPBackgroundTopMusicTagBeClickBk:)]){
                [self.delegate xsBossIPBackgroundTopMusicTagBeClickBk:tempFindTagModel];
            }
            break;
        }
    }
    
    
}

@end









